let DomEs = {}

/**
 * 获取元素
 * @param {String} selector 获取的元素 querySelector 能选择的
 */
DomEs.$ = function (selector) {
    if (selector.startsWith('#')) {
        return document.querySelector(selector)
    } else {
        return document.querySelectorAll(selector)
    }
}

/**
 * 检测类名
 * @param {NodeList} ele //元素
 * @param {String} name  //要检测的类名
 */
DomEs.hasClass = function (ele, name) {
    return ele.className.match(new RegExp('(\\s|^)' + name + '(\\s|$)'))
}

/**
 * 添加类名
 * @param {NodeList} ele //元素
 * @param {String} name  //要添加的类名
 */
DomEs.addClass = function (ele, name) {
    if (!this.hasClass(ele, name)) ele.className += ' ' + name
}

/**
 * 删除类名
 * @param {NodeList} ele //元素
 * @param {String} name  //要删除的类名
 */
DomEs.removeClass = function (ele, name) {
    if (this.hasClass(ele, name)) {
        var reg = new RegExp('(\\s|^)' + name + '(\\s|$)')
        ele.className = ele.className.replace(reg, '')
    }
}

/**
 * 替换类名
 * @param {NodeList} ele //元素
 * @param {String} oldName  //老类名
 * @param {String} newName  //新类型
 */
DomEs.replaceClass = function (ele, oldName, newName) {
    this.removeClass(ele, oldName)
    this.addClass(ele, newName)
}

/**
 * 获取元素距离body的偏移量
 * @param {NodeList} ele
 */
DomEs.offset = function (ele) {
    let offsetL = ele.offsetLeft; let offsetT = ele.offsetTop; let offsetP = ele.offsetParent
    while (offsetP) {
        offsetL += offsetP.offsetLeft
        offsetT += offsetP.offsetTop
        offsetP = offsetP.offsetParent
    }
    return {
        left: offsetL,
        top: offsetT
    }
}

/**
 * 设置css样式
 * @param {NodeList} ele
 * @param {String} attr 属性 key
 * @param {String} val 属性 value
 */
DomEs.setCss = function (el, attr, val) {
    if (attr === 'opacity') {
        el.style[attr] = val
        el.style['filter'] = 'alpha(opacity=' + val * 100 + ')'
        return
    }
    var reg = /^width|height|fontSize|(margin|padding)?(top|left|bottom|right)?$/i
    if (reg.test(attr)) {
        if (typeof val === 'number') {
            val = val + 'px'
        }
    }
    el.style[attr] = val
}

/**
 * 获取指定类名的父级元素
 * @param {NodeList} ele
 * @param {String} selector 父级选择器类型
 */
DomEs.getClassParents = function (ele, selector) {
    // parents vars element or null
    let parents = null
    let element = ele.parentNode

    // If no selector defined will bubble up all the way to *document*
    if (selector === undefined) {
        parents = document
    }

    // parents hasClass selector
    while (parents === null) {
        if (element.parentNode === document) {
            parents = element.parentNode
        } else {
            if (this.hasClass(element, selector)) {
                parents = element
            } else {
                element = element.parentNode
            }
        }
    }
    return parents
}

export default DomEs
